﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Xps.Packaging;
using System.Windows.Xps;

namespace wpfadvancedprint
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private delegate void LoadXpsMethod();//委托事件，相当于函数指针  
        private readonly FlowDocument m_doc;//流文档  
        public MainWindow()
        {
            InitializeComponent();
            m_doc = (FlowDocument)Application.LoadComponent(new Uri("PrintlearnDocument.xaml", UriKind.RelativeOrAbsolute));//从xaml文件中加载流文档对象  
            m_doc.PagePadding = new Thickness(50);//设置页面与页面之间的边距宽度  
            Dispatcher.BeginInvoke(new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);//“延后”调用，不然刚刚更改的数据不会马上
        }
        public void LoadXps()
        {
            //构造一个基于内存的xps document  
            MemoryStream ms = new MemoryStream();
            Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            Uri DocumentUri = new Uri("pack://InMemoryDocument.xps");
            PackageStore.RemovePackage(DocumentUri);
            PackageStore.AddPackage(DocumentUri, package);
            XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri);
            //将flow document写入基于内存的xps document中去  
            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);//在这里需要添加对.NET 4.0 的一些应用，比较蛋疼  
            writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator);
            //获取这个基于内存的xps document的fixed documen  
            docViewer.Document = xpsDocument.GetFixedDocumentSequence();
            //关闭基于内存的xps document  
            xpsDocument.Close();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog p = new PrintDialog();

            p.PrintDocument(((IDocumentPaginatorSource)m_doc).DocumentPaginator, "dssss");
        }  
    }
}
